#
#	genx_search.py
#
#	David Janes
#	2008.08.16
#
#	GenX - search, create and insert structured data
#

import sys
import types
import re
import pprint
import cgi
import md5
import traceback

import genx_cfg
import genx_helpers
import genx_errors
import bm_text

class SearchMixin:
	def __init__(self):
		pass

	def ActionSearch(self, searchd):
		self.headers.add_header('Content-type','text/html', charset = 'utf-8')
		self.start('200 OK', self.headers.items())

		self.working_message = "Working"
		self.working_count = 0
		self.working_in = True

		yield self.StandardHeader(title = "Search")
		yield """
<h1>Results</h1>
<style type="text/css">
#id_working {
	position: fixed;
	border: 1px solid #999;
	padding: 10px;
	width: 450px;
	background-color: #EEE;
}
</style>
<p id="id_working"></p>
<script type="text/javascript">
working_js = {
	won : function(message) {
		var e = document.getElementById('id_working');

		e.innerHTML = message;
		e.style.display = 'block';
	},

	woff : function() {
		var e = document.getElementById('id_working');
		e.style.display = 'none';
	},

	end : 0
};
</script>
"""
		try:
			for part in self._ActionSearch(searchd):
				if part == None:
					continue

				if type(part) == types.UnicodeType:
					part = part.encode('ascii', 'xmlcharrefreplace')

				yield part
		except:
			yield	"Unexpected exception:<pre>%s</pre>""" % traceback.format_exc()

		self._WorkingOff()

	def _WorkingOn(self, add):
		self.working_count += 1
		self.working_in = True
		self.working_message += add

		return	"<script type='text/javascript'>working_js.won('%s');</script>" % (
			self.working_message,
		)

	def _WorkingOff(self):
		if self.working_in:
			self.working_in = False
			return	"<script type='text/javascript'>working_js.woff();</script>"

	def _ActionSearch(self, searchd):
		rds = []
		index = 0

		#
		#	Convoluted logic to deal with the combination of generators and timeout exceptions
		#
		yield	self._WorkingOn(".")

		for retry in [ 0, 1 ]:
			if index:
				break

			try:
				yield	self._WorkingOn(".")

				for rd in searchd["module"].query(genx_cfg.cfg, searchd, self.p_search, self, retry = retry):
					if rd == None:
						yield	self._WorkingOn(".")
						continue

					yield	self._WorkingOff()
					if index == 0:
						yield """<ul>"""

					rd[genx_helpers.KEY_INDEX] = index
					index += 1

					rd["mid"] = searchd["mid"]
					rd["qid"] = self.p_qid
					rd["search"] = self.p_search
					rd["original"] = self.p_original
					rd["callbacks"] = self.p_callbacks

					rds.append(rd)

					self.StoreAsJson(
						iid = rd[genx_helpers.KEY_IID], 
						object = rd,
					)

					for field in [ genx_helpers.KEY_INDEX, genx_helpers.KEY_IMAGE_URI, 'description', 'search', 'original', ]:
						if not rd.get('li_%s' % field):
							rd['li_%s' % field] = bm_text.unicode2html(rd.get(field) or '')

					if rd.get('image_uri'):
						rd['li_image_uri'] = """<img style="float: right" src="%(image_uri)s" />""" % rd

					li = u"""\
<li class="item">
%(li_image_uri)s
<div class="title"><a href="?mid=%(mid)s&amp;action=open&amp;qid=%(qid)s&amp;iid=%(_iid)s&amp;callbacks=%(callbacks)s&amp;original=%(li_original)s">%(_list)s</a></div>
<div class="description">%(li_description)s</description>
<div style="clear: both"></div>
</li>
""" % rd

					yield	li

				break
			except genx_errors.GenXTimeoutError:
				if retry == 0:
					yield	self._WorkingOn("X")
				else:
					yield """<p class="warning">Timeout ... try again later</p>"""

		yield	self._WorkingOff()
		self.StoreAsJson(
			iid = "query",
			object = rds,
		)

		if index > 0:
			yield """</ul>"""

		if index == 0:
			yield	"""<div class="nresults">No results</div>"""
		elif index == 1:
			yield	"""<div class="nresults">1 result</div>"""
		else:
			yield	"""<div class="nresults">%d results</div>""" % index

		yield self.StandardFooter()

